<%@ taglib prefix="fmt" uri="http://java.sun.com/jstl/fmt" %>
<fmt:setBundle basename="messages.recorrido"/>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

<html>

<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">

<title>GPSou</title>

<style type="text/css">
.iconStyle
{
position:relative;
left:8px;
}

.pinStyle
{
position:relative;
top:-15px;
}
</style>

<script type="text/javascript">
//<![CDATA[

var http_request = false;

// var baseIcon = new GIcon();
// baseIcon.iconSize=new GSize(8,8);
// baseIcon.iconAnchor=new GPoint(4,4);
// baseIcon.infoWindowAnchor=new GPoint(4,0);
// var redIcon = (new GIcon(baseIcon, "/VEGPS/html/images/redSquare.png", null, ""));
var markerCurrent;
var timer=setTimeout("", 0);
var posMarkerCurrent;

var markerStart;
var markerFinish;

var dragstart=false;
var dragfinish=false;

var tramoInicial;
var tramoMedio;
var tramoFinal;
var contextmenu;

var map;
var gMarker;
var points;
var distancia;

function parseDate(str) {
  var ts=str.split(" ");
  var d=ts[0].split("-");
  var h=ts[1].split(":");
  var s=h[2].split(".");

  var fecha=new Date(Date.UTC(d[0], d[1] - 1, d[2], h[0], h[1], s[0], s[1]));

  return(fecha);
}

function center() {
	map.SetMapView(tramoMedio.GetPoints());
  	parent.zoomLevel=map.GetZoomLevel();
  	var centerPos=map.GetCenter();
  	parent.latitud=centerPos.Latitude;
  	parent.longitud=centerPos.Longitude;

	showMap();
}

function newRoute() {
	clearTimeout(timer);

	parent.ruta=parent.ruta.slice(parent.posMarkerStart, parent.posMarkerFinish + 1);
	points=points.slice(parent.posMarkerStart, parent.posMarkerFinish + 1);
	parent.posSlice+=parent.posMarkerStart;
	parent.fechas=parent.fechas.slice(parent.posMarkerStart, parent.posMarkerFinish + 1);
	parent.latitudes=parent.latitudes.slice(parent.posMarkerStart, parent.posMarkerFinish + 1);
	parent.longitudes=parent.longitudes.slice(parent.posMarkerStart, parent.posMarkerFinish + 1);
        parent.datos="";
        for(i=0; i<parent.ruta.length; i++)
	   parent.datos=parent.datos+"#"+parent.ruta[i];

	parent.posMarkerStart=0;
	parent.posMarkerFinish=points.length - 1;

	if(parent.perfilWindow!=undefined) {
		parent.perfilWindow.close();
		parent.perfilWindow=undefined;
	}

	parent.newPath=true;
	parent.newStart=false;
	parent.newFinish=false;

    	parent.document.getElementById("lblStart").innerHTML=" ";
    	parent.document.getElementById("lblFinish").innerHTML=" ";
    	parent.document.getElementById("divNewRoute").style.display="none";

	distancia=calculaDistancia(0, points.length - 1);
parent.document.getElementById("label").innerHTML="Distancia total: <b>"+Math.round(distancia*1000)/1000+" km<\/b>";

	mapNewRoute();

	return false;
}

function mapNewRoute() {
	if(markerStart != undefined) {
		map.DeleteShape(markerStart);
		markerStart=undefined;
	}
	if(markerFinish != undefined) {
		map.DeleteShape(markerFinish);
		markerFinish=undefined;
	}
	if(markerCurrent != undefined) {
		map.DeleteShape(markerCurrent);
		markerCurrent=new VEShape(VEShapeType.Pushpin, new VELatLong(0, 0));
		markerCurrent.SetCustomIcon('<div class="iconStyle"><img src="/VEGPS/html/images/redSquare.png" alt="icon"/></div>');
		map.AddShape(markerCurrent);
	}
	if(tramoInicial != undefined)
		map.DeleteShape(tramoInicial);
	if(tramoMedio != undefined)
		map.DeleteShape(tramoMedio);
	if(tramoFinal != undefined)
		map.DeleteShape(tramoFinal);

	tramoMedio=dibujaTramo(0, points.length - 1, new VEColor(0, 0, 255, 0.5));
	map.AddShape(tramoMedio);
}

function fillDatos() {
      var results=parent.ruta[posMarkerCurrent].split(";");

      var fecha=parseDate(results[0]);
      var velocidad=Math.round(results[3] / 10);
      var altitud=results[5];

      parent.document.getElementById("fecha").innerHTML=fecha.toLocaleDateString();
      parent.document.getElementById("hora").innerHTML=fecha.toLocaleTimeString();
      parent.document.getElementById("velocidad").innerHTML=velocidad + " km/h";
      parent.document.getElementById("altitud").innerHTML=altitud + " m";
}

function drawMarker(position) {
	clearTimeout(timer);

	posMarkerCurrent=position;
	markerCurrent.SetPoints([new VELatLong(parent.latitudes[posMarkerCurrent], parent.longitudes[posMarkerCurrent])]);
	timer=window.setTimeout("fillDatos();", 1000);
}

function setPosMap(x) {
	drawMarker(x);
}

function checkPoint(e) {
	var x=e.mapX;
	var y=e.mapY;
	var pixel=new VEPixel(x, y);
	var latLong=map.PixelToLatLong(pixel);
	var posLat=latLong.Latitude;
	var posLng=latLong.Longitude;
	var minDst=360;
	var dst;

	var inicio=0;
	var fin=parent.ruta.length-1;

	posMarkerCurrent=inicio;
	for(i=inicio;i<=fin;i++) {
		dst=Math.abs(parent.latitudes[i] - posLat) + Math.abs(parent.longitudes[i] - posLng);
		if(dst < minDst) {
			minDst=dst;
			posMarkerCurrent=i;
		}
	}
	
	drawMarker(posMarkerCurrent);

	if(parent.perfilWindow!=undefined)
	  try {
		parent.perfilWindow.setPosProfile(posMarkerCurrent);
	  } catch(e) {
		parent.perfilWindow=undefined;
	  }
	return(false);
}

function dragendStart() {
	parent.posMarkerStart=posMarkerCurrent;
	markerStart.SetPoints([new VELatLong(parent.latitudes[posMarkerCurrent], parent.longitudes[posMarkerCurrent])]);
        document.getElementById("lblStart").innerHTML=parseDAte(parent.fechas[parent.posMarkerStart]).toLocaleString();
	dragstart=false;
        dibujaRuta();
}

function dragendFinish() {
	parent.posMarkerFinish=posMarkerCurrent;
	markerFinish.SetPoints([new VELatLong(parent.latitudes[posMarkerCurrent], parent.longitudes[posMarkerCurrent])]);
        document.getElementById("lblFinish").innerHTML=parseDate(parent.fechas[parent.posMarkerFinish]).toLocaleString();
	dragfinish=false;
        dibujaRuta();
}

function hideMenu() {
            contextmenu.style.visibility = "hidden";
	    document.getElementById("myShim").style.visibility="hidden";
	    map.AttachEvent("onmousemove", checkPoint);
}

function inicioRuta() {
  hideMenu();

  if(posMarkerCurrent < parent.posMarkerFinish) {
    parent.document.getElementById("divNewRoute").style.display="block";
    parent.document.getElementById("nota").style.display="none";
    parent.document.getElementById("lblStart").innerHTML=parseDate(parent.fechas[posMarkerCurrent]).toLocaleString();

    mapInicioRuta();

    parent.newStart=true;
  }
}

function mapInicioRuta() {
    if(markerStart == undefined) {
	markerStart=new VEShape(VEShapeType.Pushpin, new VELatLong(parent.latitudes[posMarkerCurrent], parent.longitudes[posMarkerCurrent]));
	markerStart.SetCustomIcon('<div class="pinStyle"><img src="http://dev.virtualearth.net/mapcontrol/v6.2/i/bin/6.2.2008082210001.41/pins/poi_usergenerated.gif"/></div>');
	map.AddShape(markerStart);
    } else {
	markerStart.SetPoints([new VELatLong(parent.latitudes[posMarkerCurrent], parent.longitudes[posMarkerCurrent])]);
    }
    parent.posMarkerStart=posMarkerCurrent;

    dibujaRuta();
}

function finRuta() {
  hideMenu();

  if(posMarkerCurrent > parent.posMarkerStart) {
    parent.document.getElementById("divNewRoute").style.display="block";
    parent.document.getElementById("nota").style.display="none";
    parent.document.getElementById("lblFinish").innerHTML=parseDate(parent.fechas[posMarkerCurrent]).toLocaleString();

    mapFinRuta();

    parent.newFinish=true;
  }
}

function mapFinRuta() {
    if(markerFinish == undefined) {
	markerFinish=new VEShape(VEShapeType.Pushpin, new VELatLong(parent.latitudes[posMarkerCurrent], parent.longitudes[posMarkerCurrent]));
	markerFinish.SetCustomIcon('<div class="pinStyle"><img src="http://dev.virtualearth.net/mapcontrol/v6.2/i/bin/6.2.2008082210001.41/pins/poi_usergenerated.gif"/></div>');
	map.AddShape(markerFinish);
    } else {
	markerFinish.SetPoints([new VELatLong(parent.latitudes[posMarkerCurrent], parent.longitudes[posMarkerCurrent])]);
    }
    parent.posMarkerFinish=posMarkerCurrent;

    dibujaRuta();
}

function showMenu(e) {
	  var x, y;
	  if(e.leftMouseButton) {
		hideMenu();
		return;
	  }
	  var marker=map.GetShapeByID(e.elementID);
// map.ShowInfoBox(contextmenu, new VEPixel(0,0));
	  if((marker !=null) && ((marker == tramoInicial) || (marker == tramoMedio) || (marker == tramoFinal) ||  (marker == markerCurrent))) {
	    if(posMarkerCurrent > parent.posMarkerFinish)
		document.getElementById("lnkStart").setAttribute("class", "disabled");
	    else 
		document.getElementById("lnkStart").setAttribute("class", "context");
	    if(posMarkerCurrent < parent.posMarkerStart)
	        document.getElementById("lnkFinish").setAttribute("class", "disabled");
	    else
	        document.getElementById("lnkFinish").setAttribute("class", "context");

	    if(map.GetMapMode() == VEMapMode.Mode3D) {
		var pixel=map.LatLongToPixel(e.latLong);
		var dst;
		var minDst=360;
		var posLat=e.latLong.Latitude;
		var posLng=e.latLong.Longitude;
		x=pixel.x;
		y=pixel.y;
		for(i=0;i<parent.ruta.length;i++) {
			dst=Math.abs(parent.latitudes[i] - posLat) + Math.abs(parent.longitudes[i] - posLng);
			if(dst < minDst) {
				minDst=dst;
				posMarkerCurrent=i;
			}
		}
		drawMarker(posMarkerCurrent);
	    } else {
            	x=e.mapX;
            	y=e.mapY;
	    }
	    var bottomRight=map.LatLongToPixel(map.GetMapView().BottomRightLatLong);
            if (x > bottomRight.x - 120) {x =bottomRight.x - 120}
            if (y > bottomRight.y - 40) {y = bottomRight.y - 40}

	    contextmenu.style.left=x+map.GetLeft()+"px";
	    contextmenu.style.top=y+map.GetTop()+"px";
            contextmenu.style.visibility = "visible";
	    document.getElementById("myShim").style.left=x+map.GetLeft()+"px";
	    document.getElementById("myShim").style.top=y+map.GetTop()+"px";
	    document.getElementById("myShim").style.visibility="visible";
	    map.DetachEvent("onmousemove", checkPoint);
//	    GEvent.clearListeners(map, "singlerightclick");
	  }
}

function addShim(el) {
            var shim = document.createElement("iframe");
            shim.id = "myShim";
            shim.frameBorder = "0";
            shim.style.position = "absolute";
            shim.style.zIndex = "1";
            shim.style.top  = el.offsetTop;
            shim.style.left = el.offsetLeft;
            shim.width  = el.offsetWidth;
            shim.height = el.offsetHeight;
            shim.style.visibility = "hidden";
            el.shimElement = shim;
            el.parentNode.insertBefore(shim, el);
}

function load() {
   if(map == undefined) {
     var script;

     var head = document.getElementsByTagName("head")[0];
     script = document.createElement('script');
     script.type = 'text/javascript';
     script.id = 'mapLib';
     head.appendChild(script);
     script.src = "http://dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=6.2";

     init();
   } else {
     showMap();
   }
}

function showMap() {
     if(map.GetMapMode()!=VEMapMode.VEMapMode2D)
	map.SetMapMode(VEMapMode.Mode2D);
     var mapStyle=map.GetMapStyle();
     if(mapStyle!=VEMapStyle.Road && mapStyle!=VEMapStyle.Shaded && mapStyle!=VEMapStyle.Aerial && mapStyle!=VEMapStyle.Hybrid)
	map.SetMapStyle(VEMapStyle.Hybrid);
     var point=new VELatLong(parent.latitud, parent.longitud);
     map.SetZoomLevel(parent.zoomLevel);
     map.SetCenter(point);

     if(parent.newPath) {
        points=points.slice(parent.posSlice, parent.posSlice+parent.latitudes.length);
        parent.posSlice=0;
        parent.newPath=false;
        mapNewRoute();
	parent.newPath=false;
     }
     if(parent.newStart) {
        posMarkerCurrent=parent.posMarkerStart;
        mapInicioRuta();
	parent.newStart=false;
     }
     if(parent.newFinish) {
        posMarkerCurrent=parent.posMarkerFinish;
        mapFinRuta();
	parent.newFinish=false;
     }
}

function init() {
	var url="/VEGPS/ServletGoogleGPS?p=getRuta&desde="+parent.desde+"&hasta="+parent.hasta;

	points=[];

	contextmenu = document.createElement("div");
	contextmenu.style.left="20px";
	contextmenu.style.top="20px";
	contextmenu.style.zIndex="2";
	contextmenu.style.visibility="hidden";
	contextmenu.style.background="#ffffff";
	contextmenu.style.border="1px solid #8888FF";

	contextmenu.innerHTML = '<a href="javascript:inicioRuta()"><div id="lnkStart" class="context">&nbsp;&nbsp;<fmt:message key="limits.link.1"/>&nbsp;&nbsp;</div></a>'
		+ '<a href="javascript:finRuta()"><div id="lnkFinish" class="context">&nbsp;&nbsp;<fmt:message key="limits.link.2"/>&nbsp;&nbsp;</div></a>';

	if(parent.ruta == undefined) {
          if (window.XMLHttpRequest) { // Mozilla, Safari,...
            http_request = new XMLHttpRequest();
            if (http_request.overrideMimeType) {
                http_request.overrideMimeType('text/xml');
            }
          } else if (window.ActiveXObject) { // IE
            try {
                http_request = new ActiveXObject("Msxml2.XMLHTTP");
            } catch (e) {
                try {
                http_request = new ActiveXObject("Microsoft.XMLHTTP");
                 } catch (e) {}
            }
          }

          if (!http_request) {
            alert('Giving up :( Cannot create an XMLHTTP instance');
            return false;
          }
          http_request.onreadystatechange = alertContents;
          http_request.open('GET', url, true);
          http_request.send(null);
	} else {
	  loadMaps();
	}
}

function loadMaps() {
        parent.document.getElementById("espera").style.display="none";
        parent.document.getElementById("pagina").style.display="block";

        if(typeof(VEMap) == "undefined") {
          window.setTimeout("loadMaps();", 100);
          return;
        }

        if(map == null)
          map = new VEMap('myMap');
        try {
          map.LoadMap();
        } catch(e) {
          window.setTimeout("loadMaps();", 100);
          return;
        }

     	if(parent.newPath) {
            points=points.slice(parent.posSlice, parent.posSlice+parent.latitudes.length);
            parent.posSlice=0;
            parent.newPath=false;
	    parent.newPath=false;
	}

	markerCurrent=new VEShape(VEShapeType.Pushpin, new VELatLong(0, 0));
	markerCurrent.SetCustomIcon('<div class="iconStyle"><img src="/VEGPS/html/images/redSquare.png" alt="icon"/></div>');

//	map.SetZoomLevel(10);
//        map.SetCenter(new VELatLong(0, 0));
	map.SetMapMode(VEMapMode.Mode2D);
	map.SetMapStyle(VEMapStyle.Hybrid);

	map.AddControl(contextmenu);
	addShim(contextmenu);

	map.AttachEvent("onclick", showMenu);

        tramoMedio=dibuja();
	map.AddShape(tramoMedio);
	map.AddShape(markerCurrent);
	distancia=calculaDistancia(0, parent.ruta.length-1);
	parent.document.getElementById("label").innerHTML="<fmt:message key="distance.text"/> <b>"+Math.round(distancia*1000)/1000+" km<\/b>";

	map.AttachEvent("onmousemove", checkPoint);

	window.setTimeout("center();", 10);
}

function switchMap() {
  var mapStyle=map.GetMapStyle();
  if(mapStyle!=VEMapStyle.Birdseye && mapStyle!=VEMapStyle.BirdseyeHybrid) {
    parent.zoomLevel=map.GetZoomLevel();
    var centerPos=map.GetCenter();
    parent.latitud=centerPos.Latitude;
    parent.longitud=centerPos.Longitude;
  }
  parent.document.getElementById("GM").style.display="block";
  parent.document.getElementById("VE").style.display="none";
  parent.WIN=parent.frames["GM"];
  parent.GM.load();
}

function alertContents() {
    if (http_request.readyState == 4) {
        if (http_request.status == 200) {

            parent.datos=http_request.responseText;
    	    parent.ruta=parent.datos.split("#");
	    parent.ruta.shift();

	    if(parent.ruta.length<=0) {
	    	alert("No hay datos de recorrido en el intervalo de tiempo seleccionado");
		history.back(1);
	    } else {
		parent.posMarkerFinish=parent.ruta.length-1;

		loadMaps();
	    }
        } else {
            alert('Se ha producido un error al obtener la ruta.');
	    history.back(1);
        }
    }
}


function dibujaRuta() {
	if(tramoInicial != undefined)
		map.DeleteShape(tramoInicial);
	if(tramoMedio != undefined)
		map.DeleteShape(tramoMedio);
	if(tramoFinal != undefined)
		map.DeleteShape(tramoFinal);
	tramoInicial=dibujaTramo(0, parent.posMarkerStart, new VEColor(255, 0, 0, 0.5));
	tramoMedio=dibujaTramo(parent.posMarkerStart, parent.posMarkerFinish, new VEColor(0, 0, 255, 0.5));
	tramoFinal=dibujaTramo(parent.posMarkerFinish, parent.ruta.length - 1, new VEColor(255, 0, 0, 0.5));

	if(tramoInicial!=undefined)
	  map.AddShape(tramoInicial);
	if(tramoMedio!=undefined)
	  map.AddShape(tramoMedio);
	if(tramoFinal!=undefined)
	  map.AddShape(tramoFinal);
}

function dibujaTramo(startPoint, finishPoint, color) {
    var polylineRuta;

    if(finishPoint > startPoint) {
      polylineRuta=new VEShape(VEShapeType.Polyline, points.slice(startPoint, finishPoint+1));
      polylineRuta.SetLineColor(color);
      polylineRuta.SetLineWidth(5);
      polylineRuta.HideIcon();
    }

    return(polylineRuta);
}

function dibuja() {
    var point;
    var latitud, longitud, latitudNMEA, longitudNMEA;
    var grados;
    var polylineRuta;
    var results;

    try {
      parent.fechas = new Array(parent.ruta.length);
      parent.latitudes = new Array(parent.ruta.length);
      parent.longitudes = new Array(parent.ruta.length);

      for(i=0; i<parent.ruta.length; i++) {
        results=parent.ruta[i].split(";");

        latitudNMEA=results[1];
        longitudNMEA=results[2];

        grados=Math.floor(latitudNMEA/1000000);
        if(grados<0)
	  grados=grados+1;
        latitud=(latitudNMEA/1000000-grados)/0.6+grados;
        grados=Math.floor(longitudNMEA/1000000);
        if(grados<0)
	  grados=grados+1;
        longitud=(longitudNMEA/1000000-grados)/0.6+grados;

	parent.fechas[i]=results[0];
	parent.latitudes[i]=latitud;
	parent.longitudes[i]=longitud;

        point = new VELatLong(latitud, longitud);
        points.push(point);
      }

      polylineRuta=new VEShape(VEShapeType.Polyline, points);
      polylineRuta.SetLineWidth(5);
      polylineRuta.SetLineColor(new VEColor(0, 0, 100, 0.5));
      polylineRuta.HideIcon();

    } catch (err) {alert("ERROR: "+err.description);}

    return(polylineRuta);
}

function calculaDistancia(startPoint, finishPoint) {
    var dx, dy;

    var dst=0;
    for(i=startPoint+1;i<=finishPoint;i++) {
        dx=6370*(parent.latitudes[i]-parent.latitudes[i-1])*Math.PI/180;
        dy=6370*Math.cos(parent.latitudes[i]*Math.PI/180)*(parent.longitudes[i]-parent.longitudes[i-1])*Math.PI/180;
        dst+=Math.sqrt(Math.pow(dx,2)+Math.pow(dy,2));
    }
    return(dst);
}

//]]>
</script>

</head>

<body onunload="map.Dispose()">
  <div id="myMap" style="width: 500px; height: 300px"></div>
</body>

</html>


